package top.yehot.cmmu.swagger.aspect;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import io.swagger.models.Swagger;
import lombok.extern.slf4j.Slf4j;
import top.yehot.cmmu.swagger.config.SwaggerProperties;

/**
 * swagger 增强操作
 * 
 * @author lquan
 * @date 2022年5月17日 下午3:28:02
 */
@Slf4j
@Aspect
@Component
public class SwaggerAop {
	
	@Autowired
	private SwaggerProperties swaggerProperties;

	@Pointcut("execution(* springfox.documentation.spring.web.json.JsonSerializer.toJson(..))")
	public void v2ApiDocs() {}
	
	// 增强url:/v2/api-docs
	@Around("v2ApiDocs()")
	public Object aroundV2ApiDocs(ProceedingJoinPoint joinPoint){
		// 获取swagger配置信息
		String basePath = (null != swaggerProperties.getAppInfo() ? swaggerProperties.getAppInfo().getBasePath() : null);
		boolean enabled = swaggerProperties.getEnabled();
		// 获取方法参数
		Object[] args = joinPoint.getArgs();
		
		Object result = null;
		try {
			if (!ObjectUtils.isEmpty(args) && enabled && StringUtils.hasText(basePath)) {
				for (int i = 0; i < args.length; i++) {
					if (args[i] instanceof Swagger) {
						Swagger swagger = (Swagger) args[i];
						swagger.setBasePath(basePath + swagger.getBasePath());
						args[i] = swagger;
					}
				}
			}
			result = joinPoint.proceed(args);
		} catch (Throwable e) {
			log.error("swagger增强操作失败", e);
		}
		return result;
	}
	
}
